package v4

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"mindonmap/models"
	"mindonmap/pkgs/setting"
	"net/http"
	"strings"
	"time"

	"github.com/gin-contrib/sessions"

	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"

	"mindonmap/pkgs/e"
)

type Mainloginsform struct {
	Tid   string `json:"t_id"`
	Token string `json:"token"`
	Eid   string `json:"e_id"`
	Error int    `json:"error"`
}

type logins struct {
	Email    string `json:"email"`
	Password string `json:"password"`
	EId      string `json:"e_id"`
	Language string `json:"language"`
	Authcode string `json:"authcode"`
}
type SessionCode struct {
	Code   string `json:"code"`
	Expire int64  `json:"expire"`
}

func GetSessionCode(c *gin.Context) {
	claims := jwt.ExtractClaims(c)
	params := claims["token"].(string)
	code := e.SUCCESS

	// curl
	v := fmt.Sprintf("%s", params)
	baseurl := setting.GetLoginurl() + "/account/session/code"
	client := &http.Client{Timeout: 60 * time.Second}
	fmt.Println(baseurl, strings.NewReader(v))
	responseToken, err := client.Post(baseurl, "application/x-www-form-urlencoded", strings.NewReader(v))
	if err != nil {
		fmt.Println(err)
	}
	defer responseToken.Body.Close()
	body, err := ioutil.ReadAll(responseToken.Body)
	if err != nil {
		fmt.Println(err)
	}
	var data SessionCode
	err = json.Unmarshal(body, &data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_DATA_TYPE_MISMATCH,
			"msg":  e.GetMsg(e.ERROR_DATA_TYPE_MISMATCH),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

func GetUserInfo(c *gin.Context) {
	claims := jwt.ExtractClaims(c)
	userName := claims["username"].(string)
	params := claims["token"].(string)
	code := e.SUCCESS
	//userRoles := models.GetRoles(userName)

	// curl
	v := fmt.Sprintf("%s", params)
	fmt.Println(v)
	baseurl := setting.GetLoginurl() + "/account/profile"
	client := &http.Client{Timeout: 60 * time.Second}
	responseToken, err := client.Post(baseurl, "application/x-www-form-urlencoded", strings.NewReader(v))
	if err != nil {
		fmt.Println(err)
	}
	defer responseToken.Body.Close()
	body, err := ioutil.ReadAll(responseToken.Body)
	if err != nil {
		fmt.Println(err)
	}

	var datas models.Webinfo
	err = json.Unmarshal(body, &datas)
	var data models.JsonOut
	if err != nil {
		data = models.JsonOut{Name: userName, Avatar: "", Introduction: datas.Nickname, EmailVerified: datas.EmailVerified}
	} else {
		data = models.JsonOut{Name: userName, Avatar: datas.Picture, Introduction: datas.Nickname, EmailVerified: datas.EmailVerified}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

func Logincheck(c *gin.Context) {
	var jsons logins
	if err := c.BindJSON(&jsons); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	v := "email=" + jsons.Email + "&password=" + jsons.Password + "&e_id=" + jsons.EId
	baseurl := setting.GetLoginurl() + "/account/email/login"
	responseToken, _ := http.Post(baseurl, "application/x-www-form-urlencoded", strings.NewReader(v))
	defer responseToken.Body.Close()
	body, err := ioutil.ReadAll(responseToken.Body)
	code := e.SUCCESS
	var data Mainloginsform
	err = json.Unmarshal(body, &data)
	data.Eid = jsons.EId
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_FAIL,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_FAIL),
		})
		return
	}

	// 更新订阅信息
	SubscriptionStatus(c, "")
	// fmt.Println("#账户登录：", data)
	session := sessions.Default(c)
	session.Clear()
	session.Set("userdata", "t_id="+data.Tid+"&e_id="+jsons.EId+"&token="+data.Token)
	session.Set("user_id", data.Tid)
	session.Save()

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  "",
		"data": data,
	})
}

func Passless_login(c *gin.Context) {
	var jsons logins
	if err := c.BindJSON(&jsons); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	v := "email=" + jsons.Email + "&authcode=" + jsons.Authcode + "&e_id=" + jsons.EId
	baseurl := setting.GetLoginurl() + "/account/email/passless"
	responseToken, _ := http.Post(baseurl, "application/x-www-form-urlencoded", strings.NewReader(v))
	defer responseToken.Body.Close()
	body, err := ioutil.ReadAll(responseToken.Body)
	if err != nil {
		fmt.Println(err)
	}
	code := e.SUCCESS
	var data map[string]interface{}
	err = json.Unmarshal(body, &data)
	if err != nil {
		fmt.Println(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  "",
		"data": data,
	})
}

func GetCode(c *gin.Context) {
	var jsons logins
	if err := c.BindJSON(&jsons); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	v := "email=" + jsons.Email + "&language=" + jsons.Language + "&e_id=" + jsons.EId
	baseurl := setting.GetLoginurl() + "/account/authcode/email/passless"
	responseToken, _ := http.Post(baseurl, "application/x-www-form-urlencoded", strings.NewReader(v))
	defer responseToken.Body.Close()
	body, err := ioutil.ReadAll(responseToken.Body)

	if err != nil {
		fmt.Println(err)
	}
	code := e.SUCCESS
	var data map[string]interface{}
	err = json.Unmarshal(body, &data)
	if err != nil {
		fmt.Println(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  "",
		"data": data,
	})
}
func Register(c *gin.Context) {
	var jsons logins
	if err := c.BindJSON(&jsons); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	v := "email=" + jsons.Email + "&password=" + jsons.Password + "&e_id=" + jsons.EId
	baseurl := setting.GetLoginurl() + "/account/email/register/simple"
	responseToken, _ := http.Post(baseurl, "application/x-www-form-urlencoded", strings.NewReader(v))
	defer responseToken.Body.Close()
	body, err := ioutil.ReadAll(responseToken.Body)

	if err != nil {
		fmt.Println(err)
	}
	code := e.SUCCESS
	var data map[string]interface{}
	err = json.Unmarshal(body, &data)
	if err != nil {
		fmt.Println(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  "",
		"data": data,
	})
}
func Logout(c *gin.Context) {
	code := e.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": "success",
	})
}
